Grokking Tree Coding Patterns for Interviews
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Course Overview
Basics of Tree
Introduction to Tree
Types of Tree
BST Traversal Techniques
BST Operations
Level Order Traversal Pattern (easy)
Introduction to Level Order Traversal Pattern
Reverse Level Order Traversal (easy)
Solution: Reverse Level Order Traversal
Find Largest Value in Each Tree Row (medium)
Solution: Find Largest Value in Each Tree Row
Maximum Width of Binary Tree (medium)
Solution: Maximum Width of Binary Tree
Maximum Level Sum of a Binary Tree (medium)
Solution: Maximum Level Sum of a Binary Tree
Zigzag Traversal (medium)
Solution: Zigzag Traversal
Even Odd Tree (medium)
Solution: Even Odd Tree
N-ary Tree Level Order Traversal (hard)
Solution: N-ary Tree Level Order Traversal
Introduction to Tree Depth Pattern
Maximum Depth (or Height) of Binary Tree (easy)
Solution: Maximum Depth (or Height) of Binary Tree
Minimum Depth of a Binary Tree (easy)
Solution: Minimum Depth of a Binary Tree
Balanced Binary Tree (easy)
Solution: Balanced Binary Tree
Tree Diameter (easy)
Solution: Tree Diameter
Maximum Depth of N-ary Tree (easy)
Solution: Maximum Depth of N-ary Tree
Find maximum depth of subtree (medium)
Solution: Find maximum depth of subtree
Introduction to Root to Leaf Path Pattern
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Sum of Root To Leaf Binary Numbers (easy)
Solution: Sum of Root To Leaf Binary Numbers
Insufficient Nodes in Root to Leaf Paths (medium)
Solution: Insufficient Nodes in Root to Leaf Paths
Smallest String Starting From Leaf (medium)
Solution: Smallest String Starting From Leaf
Pseudo-Palindromic Paths in a Binary Tree (medium)
Solution: Pseudo-Palindromic Paths in a Binary Tree
All Paths for a Sum (medium)
Solution: All Paths for a Sum
Sum of Path Numbers (medium)
Solution: Sum of Path Numbers
Path With Given Sequence (medium)
Solution: Path With Given Sequence
Count Paths for a Sum (medium)
Solution: Count Paths for a Sum
Introduction to Leaf Processing Pattern
Sum of Left Leaves (easy)
Solution: Sum of Left Leaves
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Check if all leaves are at same level (medium)
Solution: Check if all leaves are at same level
Delete Leaves With a Given Value (medium)
Solution: Delete Leaves With a Given Value
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
Introduction to Tree View Pattern
Right View of a Binary Tree (medium)
Solution: Right View of a Binary Tree
Top View Of the Binary Tree (medium)
Solution: Top View Of the Binary Tree
Bottom View Of the Binary Tree (medium)
Solution: Bottom View Of the Binary Tree
Boundary of Binary Tree (medium)
Solution: Boundary of Binary Tree
Introduction to Comparison of Two Trees Pattern
Symmetric Tree (easy)
Solution: Symmetric Tree
Mirror Image Trees (medium)
Solution: Mirror Image Trees
Subtree of Another Tree (easy)
Solution: Subtree of Another Tree
Isomorphic Trees (medium)
Solution: Isomorphic Trees
Introduction to Serialize and Deserialize Tree Pattern
Serialize and Deserialize BST (medium)
Solution: Serialize and Deserialize BST
Verify Preorder Serialization of a Binary Tree (medium)
Solution: Verify Preorder Serialization of a Binary Tree
Create Binary Tree From Descriptions (medium)
Solution: Create Binary Tree From Descriptions
Serialize and Deserialize N-ary Tree (hard)
Solution: Serialize and Deserialize N-ary Tree
Solution: Maximum Level Sum of a Binary Tree

Problem Statement

You are given the root of a binary tree. The level of its root node is 1, the level of its children is 2, and so on.

Return the level x where the sum of the values of all nodes is the highest. If there are multiple levels with the same maximum sum, return the smallest level number x.

Examples

Example 1:

  • Input: root = [1, 20, 3, 4, 5, null, 8]
Image
  • Expected Output: 2
  • Explanation:
    Level 1 has nodes: [1] with sum = 1
    Level 2 has nodes: [20, 3] with sum = 20 + 3 = 23
    Level 3 has nodes: [4, 5, 8] with sum = 4 + 5 + 8 = 17
    The maximum sum is 23 at level 2.

Example 2:

  • Input: root = [10, 5, -3, 3, 2, null, 11, 3, -2, null, 1]
Image
  • Expected Output: 3
  • Explanation:
    Level 1 has nodes: [10] with sum = 10
    Level 2 has nodes: [5, -3] with sum = 5 - 3 = 2
    Level 3 has nodes: [3, 2, 11] with sum = 3 + 2 + 11 = 16
    Level 4 has nodes: [3, -2, 1] with sum = 3 - 2 + 1 = 2
    The maximum sum is 16 at level 3.

Example 3:

  • Input: root = [5, 6, 7, 8, null, null, 9, null, null, 10]
Image
  • Expected Output: 2
  • Explanation:
    Level 1 has nodes: [5] with sum = 5
    Level 2 has nodes: [6, 7] with sum = 6 + 7 = 13
    Level 3 has nodes: [8, 9] with sum = 8 + 9 = 17
    Level 4 has nodes: [10] with sum = 10
    The maximum sum is 17 at level 3.

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -105 <= Node.val <= 105

Solution

To solve this problem, we will use a level-order traversal technique, also known as Breadth-First Search (BFS). This approach is suitable because it processes each level of the tree one at a time, allowing us to calculate the sum of node values at each level efficiently. By keeping track of the sum for every level, we can easily find the level with the maximum sum.

At each level, we will compute the sum of all node values and compare it with the maximum sum found so far. If the current level's sum is higher, we update our result to the current level. This way, we ensure that we get the smallest level x with the maximum sum in a single pass through the tree.

Step-by-step Algorithm

  1. Initialization:

    • If the root is null, return 0 immediately since there are no levels in the tree.
    • Initialize a queue (queue) to help in level-order traversal. Add the root node to the queue.
    • Set maxSum to the smallest possible integer (Integer.MIN_VALUE) to store the maximum sum found so far.
    • Set resultLevel to 1 to store the level number with the maximum sum.
    • Initialize currentLevel to 1 to keep track of the current level of traversal.
  2. Start Level-Order Traversal:

    • While the queue is not empty, perform the following steps:

    1. Process Nodes at the Current Level:

      • Get the number of nodes at the current level by taking the size of the queue (levelSize).

      • Initialize currentSum to 0 to store the sum of node values at the current level.

      1. Iterate Over All Nodes at the Current Level:
        • For each node in the level (from i = 0 to i < levelSize), perform the following:
          • Remove the front node from the queue and store it in a variable (node).

          • Add the value of the node to currentSum.

          1. Add Children of the Node to the Queue:
            • If the left child of the node is not null, add it to the queue.
            • If the right child of the node is not null, add it to the queue.
    2. Update Maximum Sum and Level:

      • After processing all nodes at the current level:
        • Compare currentSum with maxSum.
        • If currentSum is greater than maxSum, update maxSum to currentSum and set resultLevel to currentLevel.
    3. Move to Next Level:

      • Increment currentLevel by 1.
  3. End of Traversal:

    • When the queue is empty, it means all levels have been processed.
  4. Return Result:

    • Return resultLevel, which contains the level with the maximum sum.

Algorithm Walkthrough

Let's walk through the algorithm using the input [10, 5, -3, 3, 2, null, 11, 3, -2, null, 1]:

  1. Initial Setup:

    • maxSum = Integer.MIN_VALUE (a very small value).
    • resultLevel = 1.
    • currentLevel = 1.
    • queue = [10] (contains only the root).
  2. Processing Level 1:

    • levelSize = 1 (only one node at level 1).
    • currentSum = 0.
    • Loop through all nodes at this level (i = 0 to levelSize-1):
      • Dequeue node 10 from the queue.
      • Add 10 to currentSum: currentSum = 10.
      • Add left child 5 to the queue.
      • Add right child -3 to the queue.
    • After processing level 1:
      • currentSum = 10.
      • maxSum is updated to 10 because 10 > Integer.MIN_VALUE.
      • resultLevel is updated to 1.
    • Increment currentLevel to 2.
    • queue = [5, -3].
  3. Processing Level 2:

    • levelSize = 2 (two nodes at level 2).
    • currentSum = 0.
    • Loop through all nodes at this level (i = 0 to levelSize-1):
      • First Iteration (i = 0):
        • Dequeue node 5 from the queue.
        • Add 5 to currentSum: currentSum = 5.
        • Add left child 3 to the queue.
        • Add right child 2 to the queue.
      • Second Iteration (i = 1):
        • Dequeue node -3 from the queue.
        • Add -3 to currentSum: currentSum = 2.
        • No left child to add.
        • Add right child 11 to the queue.
    • After processing level 2:
      • currentSum = 2.
      • maxSum remains 10 because 2 < 10.
    • Increment currentLevel to 3.
    • queue = [3, 2, 11].
  4. Processing Level 3:

    • levelSize = 3 (three nodes at level 3).
    • currentSum = 0.
    • Loop through all nodes at this level (i = 0 to levelSize-1):
      • First Iteration (i = 0):
        • Dequeue node 3 from the queue.
        • Add 3 to currentSum: currentSum = 3.
        • Add left child 3 to the queue.
        • Add right child -2 to the queue.
      • Second Iteration (i = 1):
        • Dequeue node 2 from the queue.
        • Add 2 to currentSum: currentSum = 5.
        • No left child to add.
        • Add right child 1 to the queue.
      • Third Iteration (i = 2):
        • Dequeue node 11 from the queue.
        • Add 11 to currentSum: currentSum = 16.
        • No left child to add.
        • No right child to add.
    • After processing level 3:
      • currentSum = 16.
      • maxSum is updated to 16 because 16 > 10.
      • resultLevel is updated to 3.
    • Increment currentLevel to 4.
    • queue = [3, -2, 1].
  5. Processing Level 4:

    • levelSize = 3 (three nodes at level 4).
    • currentSum = 0.
    • Loop through all nodes at this level (i = 0 to levelSize-1):
      • First Iteration (i = 0):
        • Dequeue node 3 from the queue.
        • Add 3 to currentSum: currentSum = 3.
        • No left child to add.
        • No right child to add.
      • Second Iteration (i = 1):
        • Dequeue node -2 from the queue.
        • Add -2 to currentSum: currentSum = 1.
        • No left child to add.
        • No right child to add.
      • Third Iteration (i = 2):
        • Dequeue node 1 from the queue.
        • Add 1 to currentSum: currentSum = 2.
        • No left child to add.
        • No right child to add.
    • After processing level 4:
      • currentSum = 2.
      • maxSum remains 16 because 2 < 16.
    • Increment currentLevel to 5.
    • queue is now empty.
  6. End of Traversal:

    • The queue is empty, which means all levels have been processed.
  7. Return Result:

    • resultLevel is 3, which is the level with the maximum sum.
    • The function returns 3.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

The time complexity of the solution is , where N is the number of nodes in the binary tree. This is because we perform a level-order traversal (Breadth-First Search) using a queue, which visits each node exactly once.

Space Complexity

The space complexity of the solution is , where M is the maximum number of nodes at any level in the binary tree. This space is required for the queue that stores the nodes at each level during the traversal. In the worst case (for a complete binary tree), M can be approximately N/2, but it is simplified to for asymptotic analysis.

Maximum Level Sum of a Binary Tree (medium)
Zigzag Traversal (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity